home *** CD-ROM | disk | FTP | other *** search
/ The CICA Windows Explosion! / The CICA Windows Explosion! - Disc 2.iso / nt / gd25s.zip / DIFF.C < prev    next >
C/C++ Source or Header  |  1993-11-17  |  28KB  |  999 lines

  1. /* GNU DIFF main routine.
  2.    Copyright (C) 1988, 1989, 1992, 1993 Free Software Foundation, Inc.
  3.  
  4. This file is part of GNU DIFF.
  5.  
  6. GNU DIFF is free software; you can redistribute it and/or modify
  7. it under the terms of the GNU General Public License as published by
  8. the Free Software Foundation; either version 2, or (at your option)
  9. any later version.
  10.  
  11. GNU DIFF is distributed in the hope that it will be useful,
  12. but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. GNU General Public License for more details.
  15.  
  16. You should have received a copy of the GNU General Public License
  17. along with GNU DIFF; see the file COPYING.  If not, write to
  18. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  19.  
  20. /* GNU DIFF was written by Mike Haertel, David Hayes,
  21.    Richard Stallman, Len Tower, and Paul Eggert.  */
  22.  
  23. #define GDIFF_MAIN
  24. #include "diff.h"
  25. #include "getopt.h"
  26. #include "fnmatch.h"
  27.  
  28. #ifndef DEFAULT_WIDTH
  29. #define DEFAULT_WIDTH 130
  30. #endif
  31.  
  32. #ifndef GUTTER_WIDTH_MINIMUM
  33. #define GUTTER_WIDTH_MINIMUM 3
  34. #endif
  35.  
  36. static char const *filetype PARAMS((struct stat const *));
  37. static char *option_list PARAMS((char **, int));
  38. static int add_exclude_file PARAMS((char const *));
  39. static int ck_atoi PARAMS((char const *, int *));
  40. static int compare_files PARAMS((char const *, char const *, char const *, char const *, int));
  41. static int specify_format PARAMS((char **, char *));
  42. static void add_exclude PARAMS((char const *));
  43. static void add_regexp PARAMS((struct regexp_list **, char const *));
  44. static void specify_style PARAMS((enum output_style));
  45. static void usage PARAMS((void));
  46.  
  47. /* Nonzero for -r: if comparing two directories,
  48.    compare their common subdirectories recursively.  */
  49.  
  50. static int recursive;
  51.  
  52. /* For debugging: don't do discard_confusing_lines.  */
  53.  
  54. int no_discards;
  55.  
  56. /* Return a string containing the command options with which diff was invoked.
  57.    Spaces appear between what were separate ARGV-elements.
  58.    There is a space at the beginning but none at the end.
  59.    If there were no options, the result is an empty string.
  60.  
  61.    Arguments: OPTIONVEC, a vector containing separate ARGV-elements, and COUNT,
  62.    the length of that vector.  */
  63.  
  64. static char *
  65. option_list (optionvec, count)
  66.      char **optionvec;  /* Was `vector', but that collides on Alliant.  */
  67.      int count;
  68. {
  69.   int i;
  70.   size_t length = 0;
  71.   char *result;
  72.  
  73.   for (i = 0; i < count; i++)
  74.     length += strlen (optionvec[i]) + 1;
  75.  
  76.   result = xmalloc (length + 1);
  77.   result[0] = 0;
  78.  
  79.   for (i = 0; i < count; i++)
  80.     {
  81.       strcat (result, " ");
  82.       strcat (result, optionvec[i]);
  83.     }
  84.  
  85.   return result;
  86. }
  87.  
  88. /* Convert STR to a positive integer, storing the result in *OUT.
  89.    If STR is not a valid integer, return -1 (otherwise 0). */
  90. static int
  91. ck_atoi (str, out)
  92.      char const *str;
  93.      int *out;
  94. {
  95.   char const *p;
  96.   for (p = str; *p; p++)
  97.     if (*p < '0' || *p > '9')
  98.       return -1;
  99.  
  100.   *out = atoi (optarg);
  101.   return 0;
  102. }
  103.  
  104. /* Keep track of excluded file name patterns.  */
  105.  
  106. static char const **exclude;
  107. static int exclude_alloc, exclude_count;
  108.  
  109. int
  110. excluded_filename (f)
  111.      char const *f;
  112. {
  113.   int i;
  114.   for (i = 0;  i < exclude_count;  i++)
  115.     if (fnmatch (exclude[i], f, 0) == 0)
  116.       return 1;
  117.   return 0;
  118. }
  119.  
  120. static void
  121. add_exclude (pattern)
  122.      char const *pattern;
  123. {
  124.   if (exclude_alloc <= exclude_count)
  125.     exclude = (char const **)
  126.           (exclude_alloc == 0
  127.            ? xmalloc ((exclude_alloc = 64) * sizeof (*exclude))
  128.            : xrealloc (exclude, (exclude_alloc *= 2) * sizeof (*exclude)));
  129.  
  130.   exclude[exclude_count++] = pattern;
  131. }
  132.  
  133. static int
  134. add_exclude_file (name)
  135.      char const *name;
  136. {
  137.   struct file_data f;
  138.   char *p, *q, *lim;
  139.  
  140.   f.name = optarg;
  141.   f.desc = (strcmp (optarg, "-") == 0
  142.         ? STDIN_FILENO
  143.         : open (optarg, O_RDONLY, 0));
  144.   if (f.desc < 0 || fstat (f.desc, &f.stat) != 0)
  145.     return -1;
  146.  
  147.   sip (&f, 1);
  148.   slurp (&f);
  149.  
  150.   for (p = (char *)f.buffer, lim = p + f.buffered_chars;  p < lim;  p = q)
  151.     {
  152.       q = (char *) memchr (p, '\n', lim - p);
  153.       if (!q)
  154.     q = lim;
  155.       *q++ = 0;
  156.       add_exclude (p);
  157.     }
  158.  
  159.   return close (f.desc);
  160. }
  161.  
  162. /* The numbers 129- that appear in the fourth element of some entries
  163.    tell the big switch in `main' how to process those options.  */
  164.  
  165. static struct option const longopts[] =
  166. {
  167.   {"ignore-blank-lines", 0, 0, 'B'},
  168.   {"context", 2, 0, 'C'},
  169.   {"ifdef", 1, 0, 'D'},
  170.   {"show-function-line", 1, 0, 'F'},
  171.   {"speed-large-files", 0, 0, 'H'},
  172.   {"ignore-matching-lines", 1, 0, 'I'},
  173.   {"label", 1, 0, 'L'},
  174.   {"file-label", 1, 0, 'L'},    /* An alias, no longer recommended */
  175.   {"new-file", 0, 0, 'N'},
  176.   {"entire-new-file", 0, 0, 'N'},    /* An alias, no longer recommended */
  177.   {"unidirectional-new-file", 0, 0, 'P'},
  178.   {"starting-file", 1, 0, 'S'},
  179.   {"initial-tab", 0, 0, 'T'},
  180.   {"width", 1, 0, 'W'},
  181.   {"text", 0, 0, 'a'},
  182.   {"ascii", 0, 0, 'a'},        /* An alias, no longer recommended */
  183.   {"ignore-space-change", 0, 0, 'b'},
  184.   {"minimal", 0, 0, 'd'},
  185.   {"ed", 0, 0, 'e'},
  186.   {"forward-ed", 0, 0, 'f'},
  187.   {"ignore-case", 0, 0, 'i'},
  188.   {"paginate", 0, 0, 'l'},
  189.   {"print", 0, 0, 'l'},        /* An alias, no longer recommended */
  190.   {"rcs", 0, 0, 'n'},
  191.   {"show-c-function", 0, 0, 'p'},
  192.   {"binary", 0, 0, 'q'},    /* An alias, no longer recommended */
  193.   {"brief", 0, 0, 'q'},
  194.   {"recursive", 0, 0, 'r'},
  195.   {"report-identical-files", 0, 0, 's'},
  196.   {"expand-tabs", 0, 0, 't'},
  197.   {"version", 0, 0, 'v'},
  198.   {"ignore-all-space", 0, 0, 'w'},
  199.   {"exclude", 1, 0, 'x'},
  200.   {"exclude-from", 1, 0, 'X'},
  201.   {"side-by-side", 0, 0, 'y'},
  202.   {"unified", 2, 0, 'U'},
  203.   {"left-column", 0, 0, 129},
  204.   {"suppress-common-lines", 0, 0, 130},
  205.   {"sdiff-merge-assist", 0, 0, 131},
  206.   {"old-line-format", 1, 0, 132},
  207.   {"new-line-format", 1, 0, 133},
  208.   {"unchanged-line-format", 1, 0, 134},
  209.   {"line-format", 1, 0, 135},
  210.   {"old-group-format", 1, 0, 136},
  211.   {"new-group-format", 1, 0, 137},
  212.   {"unchanged-group-format", 1, 0, 138},
  213.   {"changed-group-format", 1, 0, 139},
  214.   {"horizon-lines", 1, 0, 140},
  215.   {0, 0, 0, 0}
  216. };
  217.  
  218. int
  219. main (argc, argv)
  220.      int argc;
  221.      char *argv[];
  222. {
  223.   int val;
  224.   int c;
  225.   int prev = -1;
  226.   int width = DEFAULT_WIDTH;
  227.  
  228.   /* Do our initializations.  */
  229.   program = argv[0];
  230.   output_style = OUTPUT_NORMAL;
  231.   context = -1;
  232.   line_end_char = '\n';
  233.  
  234.   /* Decode the options.  */
  235.  
  236.   while ((c = getopt_long (argc, argv,
  237.                "0123456789abBcC:dD:efF:hHiI:lL:nNpPqrsS:tTuU:vwW:x:X:y",
  238.                longopts, 0)) != EOF)
  239.     {
  240.       switch (c)
  241.     {
  242.       /* All digits combine in decimal to specify the context-size.  */
  243.     case '1':
  244.     case '2':
  245.     case '3':
  246.     case '4':
  247.     case '5':
  248.     case '6':
  249.     case '7':
  250.     case '8':
  251.     case '9':
  252.     case '0':
  253.       if (context == -1)
  254.         context = 0;
  255.       /* If a context length has already been specified,
  256.          more digits allowed only if they follow right after the others.
  257.          Reject two separate runs of digits, or digits after -C.  */
  258.       else if (prev < '0' || prev > '9')
  259.         fatal ("context length specified twice");
  260.  
  261.       context = context * 10 + c - '0';
  262.       break;
  263.  
  264.     case 'a':
  265.       /* Treat all files as text files; never treat as binary.  */
  266.       always_text_flag = 1;
  267.       setmode(0, O_BINARY);
  268.       setmode(1, O_BINARY);
  269.  
  270.       break;
  271.  
  272.     case 'b':
  273.       /* Ignore changes in amount of white space.  */
  274.       ignore_space_change_flag = 1;
  275.       length_varies = 1;
  276.       ignore_some_changes = 1;
  277.       break;
  278.  
  279.     case 'B':
  280.       /* Ignore changes affecting only blank lines.  */
  281.       ignore_blank_lines_flag = 1;
  282.       ignore_some_changes = 1;
  283.       break;
  284.  
  285.     case 'C':        /* +context[=lines] */
  286.     case 'U':        /* +unified[=lines] */
  287.       if (optarg)
  288.         {
  289.           if (context >= 0)
  290.         fatal ("context length specified twice");
  291.  
  292.           if (ck_atoi (optarg, &context))
  293.         fatal ("invalid context length argument");
  294.         }
  295.  
  296.       /* Falls through.  */
  297.     case 'c':
  298.       /* Make context-style output.  */
  299.       specify_style (c == 'U' ? OUTPUT_UNIFIED : OUTPUT_CONTEXT);
  300.       break;
  301.  
  302.     case 'd':
  303.       /* Don't discard lines.  This makes things slower (sometimes much
  304.          slower) but will find a guaranteed minimal set of changes.  */
  305.       no_discards = 1;
  306.       break;
  307.  
  308.     case 'D':
  309.       /* Make merged #ifdef output.  */
  310.       specify_style (OUTPUT_IFDEF);
  311.       {
  312.         int i, err = 0;
  313.         static char const C_ifdef_group_formats[] =
  314.           "#ifndef %s\n%%<#endif /* not %s */\n%c#ifdef %s\n%%>#endif /* %s */\n%c%%=%c#ifndef %s\n%%<#else /* %s */\n%%>#endif /* %s */\n";
  315.         char *b = xmalloc (sizeof (C_ifdef_group_formats)
  316.                    + 7 * strlen(optarg) - 14 /* 7*"%s" */
  317.                    - 8 /* 5*"%%" + 3*"%c" */);
  318.         sprintf (b, C_ifdef_group_formats,
  319.              optarg, optarg, 0,
  320.              optarg, optarg, 0, 0,
  321.              optarg, optarg, optarg);
  322.         for (i = 0; i < 4; i++)
  323.           {
  324.         err |= specify_format (&group_format[i], b);
  325.         b += strlen (b) + 1;
  326.           }
  327.         if (err)
  328.           error ("conflicting #ifdef formats", 0, 0);
  329.       }
  330.       break;
  331.  
  332.     case 'e':
  333.       /* Make output that is a valid `ed' script.  */
  334.       specify_style (OUTPUT_ED);
  335.       break;
  336.  
  337.     case 'f':
  338.       /* Make output that looks vaguely like an `ed' script
  339.          but has changes in the order they appear in the file.  */
  340.       specify_style (OUTPUT_FORWARD_ED);
  341.       break;
  342.  
  343.     case 'F':
  344.       /* Show, for each set of changes, the previous line that
  345.          matches the specified regexp.  Currently affects only
  346.          context-style output.  */
  347.       add_regexp (&function_regexp_list, optarg);
  348.       break;
  349.  
  350.     case 'h':
  351.       /* Split the files into chunks of around 1500 lines
  352.          for faster processing.  Usually does not change the result.
  353.  
  354.          This currently has no effect.  */
  355.       break;
  356.  
  357.     case 'H':
  358.       /* Turn on heuristics that speed processing of large files
  359.          with a small density of changes.  */
  360.       heuristic = 1;
  361.       break;
  362.  
  363.     case 'i':
  364.       /* Ignore changes in case.  */
  365.       ignore_case_flag = 1;
  366.       ignore_some_changes = 1;
  367.       break;
  368.  
  369.     case 'I':
  370.       /* Ignore changes affecting only lines that match the
  371.          specified regexp.  */
  372.       add_regexp (&ignore_regexp_list, optarg);
  373.       ignore_some_changes = 1;
  374.       break;
  375.  
  376.     case 'l':
  377.       /* Pass the output through `pr' to paginate it.  */
  378.       paginate_flag = 1;
  379.       break;
  380.  
  381.     case 'L':
  382.       /* Specify file labels for `-c' output headers.  */
  383.       if (!file_label[0])
  384.         file_label[0] = optarg;
  385.       else if (!file_label[1])
  386.         file_label[1] = optarg;
  387.       else
  388.         fatal ("too many file label options");
  389.       break;
  390.  
  391.     case 'n':
  392.       /* Output RCS-style diffs, like `-f' except that each command
  393.          specifies the number of lines affected.  */
  394.       specify_style (OUTPUT_RCS);
  395.       break;
  396.  
  397.     case 'N':
  398.       /* When comparing directories, if a file appears only in one
  399.          directory, treat it as present but empty in the other.  */
  400.       entire_new_file_flag = 1;
  401.       break;
  402.  
  403.     case 'p':
  404.       /* Make context-style output and show name of last C function.  */
  405.       specify_style (OUTPUT_CONTEXT);
  406.       add_regexp (&function_regexp_list, "^[_a-zA-Z$]");
  407.       break;
  408.  
  409.     case 'P':
  410.       /* When comparing directories, if a file appears only in
  411.          the second directory of the two,
  412.          treat it as present but empty in the other.  */
  413.       unidirectional_new_file_flag = 1;
  414.       break;
  415.  
  416.     case 'q':
  417.       no_details_flag = 1;
  418.       break;
  419.  
  420.     case 'r':
  421.       /* When comparing directories,
  422.          recursively compare any subdirectories found.  */
  423.       recursive = 1;
  424.       break;
  425.  
  426.     case 's':
  427.       /* Print a message if the files are the same.  */
  428.       print_file_same_flag = 1;
  429.       break;
  430.  
  431.     case 'S':
  432.       /* When comparing directories, start with the specified
  433.          file name.  This is used for resuming an aborted comparison.  */
  434.       dir_start_file = optarg;
  435.       break;
  436.  
  437.     case 't':
  438.       /* Expand tabs to spaces in the output so that it preserves
  439.          the alignment of the input files.  */
  440.       tab_expand_flag = 1;
  441.       break;
  442.  
  443.     case 'T':
  444.       /* Use a tab in the output, rather than a space, before the
  445.          text of an input line, so as to keep the proper alignment
  446.          in the input line without changing the characters in it.  */
  447.       tab_align_flag = 1;
  448.       break;
  449.  
  450.     case 'u':
  451.       /* Output the context diff in unidiff format.  */
  452.       specify_style (OUTPUT_UNIFIED);
  453.       break;
  454.  
  455.     case 'v':
  456.       fprintf (stderr, "GNU diff version %s\n", version_string);
  457.       break;
  458.  
  459.     case 'w':
  460.       /* Ignore horizontal white space when comparing lines.  */
  461.       ignore_all_space_flag = 1;
  462.       ignore_some_changes = 1;
  463.       length_varies = 1;
  464.       break;
  465.  
  466.     case 'x':
  467.       add_exclude (optarg);
  468.       break;
  469.  
  470.     case 'X':
  471.       if (add_exclude_file (optarg) != 0)
  472.         pfatal_with_name (optarg);
  473.       break;
  474.  
  475.     case 'y':
  476.       /* Use side-by-side (sdiff-style) columnar output. */
  477.       specify_style (OUTPUT_SDIFF);
  478.       break;
  479.  
  480.     case 'W':
  481.       /* Set the line width for OUTPUT_SDIFF.  */
  482.       if (ck_atoi (optarg, &width) || width <= 0)
  483.         fatal ("column width must be a positive integer");
  484.       break;
  485.  
  486.     case 129:
  487.       sdiff_left_only = 1;
  488.       break;
  489.  
  490.     case 130:
  491.       sdiff_skip_common_lines = 1;
  492.       break;
  493.  
  494.     case 131:
  495.       /* sdiff-style columns output. */
  496.       specify_style (OUTPUT_SDIFF);
  497.       sdiff_help_sdiff = 1;
  498.       break;
  499.  
  500.     case 132:
  501.     case 133:
  502.     case 134:
  503.       specify_style (OUTPUT_IFDEF);
  504.       if (specify_format (&line_format[c - 132], optarg) != 0)
  505.         error ("conflicting line format", 0, 0);
  506.       break;
  507.  
  508.     case 135:
  509.       specify_style (OUTPUT_IFDEF);
  510.       {
  511.         int i, err = 0;
  512.         for (i = 0; i < sizeof (line_format) / sizeof (*line_format); i++)
  513.           err |= specify_format (&line_format[i], optarg);
  514.         if (err)
  515.           error ("conflicting line format", 0, 0);
  516.       }
  517.       break;
  518.  
  519.     case 136:
  520.     case 137:
  521.     case 138:
  522.     case 139:
  523.       specify_style (OUTPUT_IFDEF);
  524.       if (specify_format (&group_format[c - 136], optarg) != 0)
  525.         error ("conflicting group format", 0, 0);
  526.       break;
  527.  
  528.     case 140:
  529.       if (ck_atoi (optarg, &horizon_lines) || horizon_lines < 0)
  530.         fatal ("horizon must be a nonnegative integer");
  531.       break;
  532.  
  533.     default:
  534.       usage ();
  535.     }
  536.       prev = c;
  537.     }
  538.  
  539.   if (optind != argc - 2)
  540.     usage ();
  541.  
  542.  
  543.   {
  544.     /*
  545.      *    We maximize first the half line width, and then the gutter width,
  546.      *    according to the following constraints:
  547.      *    1.  Two half lines plus a gutter must fit in a line.
  548.      *    2.  If the half line width is nonzero:
  549.      *        a.  The gutter width is at least GUTTER_WIDTH_MINIMUM.
  550.      *        b.  If tabs are not expanded to spaces,
  551.      *        a half line plus a gutter is an integral number of tabs,
  552.      *        so that tabs in the right column line up.
  553.      */
  554.     int t = tab_expand_flag ? 1 : TAB_WIDTH;
  555.     int off = (width + t + GUTTER_WIDTH_MINIMUM) / (2*t)  *  t;
  556.     sdiff_half_width = max (0, min (off - GUTTER_WIDTH_MINIMUM, width - off)),
  557.     sdiff_column2_offset = sdiff_half_width ? off : width;
  558.   }
  559.  
  560.   if (output_style != OUTPUT_CONTEXT && output_style != OUTPUT_UNIFIED)
  561.     context = 0;
  562.   else if (context == -1)
  563.     /* Default amount of context for -c.  */
  564.     context = 3;
  565.  
  566.   if (output_style == OUTPUT_IFDEF)
  567.     {
  568.       int i;
  569.       for (i = 0; i < sizeof (line_format) / sizeof (*line_format); i++)
  570.     if (!line_format[i])
  571.       line_format[i] = "%l\n";
  572.       if (!group_format[OLD])
  573.     group_format[OLD]
  574.       = group_format[UNCHANGED] ? group_format[UNCHANGED] : "%<";
  575.       if (!group_format[NEW])
  576.     group_format[NEW]
  577.       = group_format[UNCHANGED] ? group_format[UNCHANGED] : "%>";
  578.       if (!group_format[UNCHANGED])
  579.     group_format[UNCHANGED] = "%=";
  580.       if (!group_format[CHANGED])
  581.     group_format[CHANGED] = concat (group_format[OLD],
  582.                     group_format[NEW], "");
  583.     }
  584.  
  585.   no_diff_means_no_output =
  586.     (output_style == OUTPUT_IFDEF ?
  587.       (!*group_format[UNCHANGED]
  588.        || (strcmp (group_format[UNCHANGED], "%=") == 0
  589.        && !*line_format[UNCHANGED]))
  590.      : output_style == OUTPUT_SDIFF ? sdiff_skip_common_lines : 1);
  591.  
  592.   switch_string = option_list (argv + 1, optind - 1);
  593.  
  594.   val = compare_files (0, argv[optind], 0, argv[optind + 1], 0);
  595.  
  596.   /* Print any messages that were saved up for last.  */
  597.   print_message_queue ();
  598.  
  599.   if (ferror (stdout) || fclose (stdout) != 0)
  600.     fatal ("write error");
  601.   exit (val);
  602.   return val;
  603. }
  604.  
  605. /* Add the compiled form of regexp PATTERN to REGLIST.  */
  606.  
  607. static void
  608. add_regexp (reglist, pattern)
  609.      struct regexp_list **reglist;
  610.      char const *pattern;
  611. {
  612.   struct regexp_list *r;
  613.   char const *m;
  614.  
  615.   r = (struct regexp_list *) xmalloc (sizeof (*r));
  616.   bzero (r, sizeof (*r));
  617.   r->buf.fastmap = xmalloc (256);
  618.   m = re_compile_pattern (pattern, strlen (pattern), &r->buf);
  619.   if (m != 0)
  620.     error ("%s: %s", pattern, m);
  621.  
  622.   /* Add to the start of the list, since it's easier than the end.  */
  623.   r->next = *reglist;
  624.   *reglist = r;
  625. }
  626.  
  627. static void
  628. usage ()
  629. {
  630.   fprintf (stderr, "Usage: %s [options] from-file to-file\n", program);
  631.   fprintf (stderr, "Options:\n\
  632.     [-abBcdefhHilnNpPqrstTuvwy] [-C lines] [-D name] [-F regexp]\n\
  633.     [-I regexp] [-L from-label [-L to-label]] [-S starting-file] [-U lines]\n\
  634.     [-W columns] [-x pattern] [-X pattern-file]\n");
  635.   fprintf (stderr, "\
  636.     [--brief] [--changed-group-format=format] [--context[=lines]] [--ed]\n\
  637.     [--exclude=pattern] [--exclude-from=pattern-file] [--expand-tabs]\n\
  638.     [--forward-ed] [--horizon-lines=lines] [--ifdef=name]\n\
  639.     [--ignore-all-space] [--ignore-blank-lines] [--ignore-case]\n");
  640.   fprintf (stderr, "\
  641.     [--ignore-matching-lines=regexp] [--ignore-space-change]\n\
  642.     [--initial-tab] [--label=from-label [--label=to-label]]\n\
  643.     [--left-column] [--minimal] [--new-file] [--new-group-format=format]\n\
  644.     [--new-line-format=format] [--old-group-format=format]\n");
  645.   fprintf (stderr, "\
  646.     [--old-line-format=format] [--paginate] [--rcs] [--recursive]\n\
  647.     [--report-identical-files] [--sdiff-merge-assist] [--show-c-function]\n\
  648.     [--show-function-line=regexp] [--side-by-side] [--speed-large-files]\n\
  649.     [--starting-file=starting-file] [--suppress-common-lines] [--text]\n");
  650.   fprintf (stderr, "\
  651.     [--unchanged-group-format=format] [--unchanged-line-format=format]\n\
  652.     [--unidirectional-new-file] [--unified[=lines]] [--version]\n\
  653.     [--width=columns]\n");
  654.   exit (2);
  655. }
  656.  
  657. static int
  658. specify_format (var, value)
  659.      char **var;
  660.      char *value;
  661. {
  662.   int err = *var ? strcmp (*var, value) : 0;
  663.   *var = value;
  664.   return err;
  665. }
  666.  
  667. static void
  668. specify_style (style)
  669.      enum output_style style;
  670. {
  671.   if (output_style != OUTPUT_NORMAL
  672.       && output_style != style)
  673.     error ("conflicting specifications of output style", 0, 0);
  674.   output_style = style;
  675. }
  676.  
  677. static char const *
  678. filetype (st)
  679.      struct stat const *st;
  680. {
  681.   /* See Posix.2 section 4.17.6.1.1 and Table 5-1 for these formats.
  682.      To keep diagnostics grammatical, the returned string must start
  683.      with a consonant.  */
  684.  
  685.   if (S_ISREG (st->st_mode))
  686.     {
  687.       if (st->st_size == 0)
  688.     return "regular empty file";
  689.       /* Posix.2 section 5.14.2 seems to suggest that we must read the file
  690.      and guess whether it's C, Fortran, etc., but this is somewhat useless
  691.      and doesn't reflect historical practice.  We're allowed to guess
  692.      wrong, so we don't bother to read the file.  */
  693.       return "regular file";
  694.     }
  695.   if (S_ISDIR (st->st_mode)) return "directory";
  696.  
  697.   /* other Posix.1 file types */
  698. #ifdef S_ISBLK
  699.   if (S_ISBLK (st->st_mode)) return "block special file";
  700. #endif
  701. #ifdef S_ISCHR
  702.   if (S_ISCHR (st->st_mode)) return "character special file";
  703. #endif
  704. #ifdef S_ISFIFO
  705.   if (S_ISFIFO (st->st_mode)) return "fifo";
  706. #endif
  707.  
  708.   /* other popular file types */
  709.   /* S_ISLNK is impossible with `stat'.  */
  710. #ifdef S_ISSOCK
  711.   if (S_ISSOCK (st->st_mode)) return "socket";
  712. #endif
  713.  
  714.   return "weird file";
  715. }
  716.  
  717. /* Compare two files (or dirs) with specified names
  718.    DIR0/NAME0 and DIR1/NAME1, at level DEPTH in directory recursion.
  719.    (if DIR0 is 0, then the name is just NAME0, etc.)
  720.    This is self-contained; it opens the files and closes them.
  721.  
  722.    Value is 0 if files are the same, 1 if different,
  723.    2 if there is a problem opening them.  */
  724.  
  725. static int
  726. compare_files (dir0, name0, dir1, name1, depth)
  727.      char const *dir0, *dir1;
  728.      char const *name0, *name1;
  729.      int depth;
  730. {
  731.   struct file_data inf[2];
  732.   register int i;
  733.   int val;
  734.   int same_files;
  735.   int failed = 0;
  736.   char *free0 = 0, *free1 = 0;
  737.  
  738.   /* If this is directory comparison, perhaps we have a file
  739.      that exists only in one of the directories.
  740.      If so, just print a message to that effect.  */
  741.  
  742.   if (! ((name0 != 0 && name1 != 0)
  743.      || (unidirectional_new_file_flag && name1 != 0)
  744.      || entire_new_file_flag))
  745.     {
  746.       char const *name = name0 == 0 ? name1 : name0;
  747.       char const *dir = name0 == 0 ? dir1 : dir0;
  748.       message ("Only in %s: %s\n", dir, name);
  749.       /* Return 1 so that diff_dirs will return 1 ("some files differ").  */
  750.       return 1;
  751.     }
  752.  
  753.   /* Mark any nonexistent file with -1 in the desc field.  */
  754.   /* Mark unopened files (e.g. directories) with -2. */
  755.  
  756.   inf[0].desc = name0 == 0 ? -1 : -2;
  757.   inf[1].desc = name1 == 0 ? -1 : -2;
  758.  
  759.   /* Now record the full name of each file, including nonexistent ones.  */
  760.  
  761.   if (name0 == 0)
  762.     name0 = name1;
  763.   if (name1 == 0)
  764.     name1 = name0;
  765.  
  766.   inf[0].name = dir0 == 0 ? name0 : (free0 = dir_file_pathname (dir0, name0));
  767.   inf[1].name = dir1 == 0 ? name1 : (free1 = dir_file_pathname (dir1, name1));
  768.  
  769.   /* Stat the files.  Record whether they are directories.  */
  770.  
  771.   for (i = 0; i <= 1; i++)
  772.     {
  773.       bzero (&inf[i].stat, sizeof (struct stat));
  774.       inf[i].dir_p = 0;
  775.  
  776.       if (inf[i].desc != -1)
  777.     {
  778.       int stat_result;
  779.  
  780.       if (i && strcmp (inf[i].name, inf[0].name) == 0)
  781.         {
  782.           inf[i].stat = inf[0].stat;
  783.           stat_result = 0;
  784.         }
  785.       else if (strcmp (inf[i].name, "-") == 0)
  786.         {
  787.           inf[i].desc = STDIN_FILENO;
  788.           stat_result = fstat (STDIN_FILENO, &inf[i].stat);
  789.           if (stat_result == 0 && S_ISREG (inf[i].stat.st_mode))
  790.         {
  791.           off_t pos = lseek (STDIN_FILENO, (off_t) 0, SEEK_CUR);
  792.           if (pos == -1)
  793.             stat_result = -1;
  794.           else
  795.             {
  796.               if (pos <= inf[i].stat.st_size)
  797.             inf[i].stat.st_size -= pos;
  798.               else
  799.             inf[i].stat.st_size = 0;
  800.               /* Posix.2 4.17.6.1.4 requires current time for stdin.  */
  801.               time (&inf[i].stat.st_mtime);
  802.             }
  803.         }
  804.         }
  805.       else
  806.         stat_result = stat (inf[i].name, &inf[i].stat);
  807.  
  808.       if (stat_result != 0)
  809.         {
  810.           perror_with_name (inf[i].name);
  811.           failed = 1;
  812.         }
  813.       else
  814.         {
  815.           inf[i].dir_p = S_ISDIR (inf[i].stat.st_mode) && inf[i].desc != 0;
  816.           if (inf[1 - i].desc == -1)
  817.         {
  818.           inf[1 - i].dir_p = inf[i].dir_p;
  819.           inf[1 - i].stat.st_mode = inf[i].stat.st_mode;
  820.         }
  821.         }
  822.     }
  823.     }
  824.  
  825.   if (! failed && depth == 0 && inf[0].dir_p != inf[1].dir_p)
  826.     {
  827.       /* If one is a directory, and it was specified in the command line,
  828.      use the file in that dir with the other file's basename.  */
  829.  
  830.       int fnm_arg = inf[0].dir_p;
  831.       int dir_arg = 1 - fnm_arg;
  832.       char const *fnm = inf[fnm_arg].name;
  833.       char const *dir = inf[dir_arg].name;
  834.       char const *p = strrchr (fnm, '/');
  835.       char const *filename = inf[dir_arg].name
  836.     = dir_file_pathname (dir, p ? p + 1 : fnm);
  837.  
  838.       if (strcmp (fnm, "-") == 0)
  839.     fatal ("can't compare - to a directory");
  840.  
  841.       if (stat (filename, &inf[dir_arg].stat) != 0)
  842.     {
  843.       perror_with_name (filename);
  844.       failed = 1;
  845.     }
  846.       else
  847.     inf[dir_arg].dir_p = S_ISDIR (inf[dir_arg].stat.st_mode);
  848.     }
  849.  
  850.   if (failed)
  851.     {
  852.  
  853.       /* If either file should exist but does not, return 2.  */
  854.  
  855.       val = 2;
  856.  
  857.     }
  858. #if defined(__MSDOS__) || defined(__NT__)
  859.   else if (same_files = 0) /* yes, only ONE equal sign intended! hmo11apr93 */
  860.     ;
  861. #else
  862.   else if ((same_files =    inf[0].stat.st_ino == inf[1].stat.st_ino
  863.              && inf[0].stat.st_dev == inf[1].stat.st_dev
  864.              && inf[0].stat.st_size == inf[1].stat.st_size
  865.              && inf[0].desc != -1
  866.              && inf[1].desc != -1)
  867.        && no_diff_means_no_output)
  868.     {
  869.       /* The two named files are actually the same physical file.
  870.      We know they are identical without actually reading them.  */
  871.  
  872.       val = 0;
  873.     }
  874. #endif /*__MSDOS__||__NT__*/
  875.   else if (inf[0].dir_p & inf[1].dir_p)
  876.     {
  877.       if (output_style == OUTPUT_IFDEF)
  878.     fatal ("-D option not supported with directories");
  879.  
  880.       /* If both are directories, compare the files in them.  */
  881.  
  882.       if (depth > 0 && !recursive)
  883.     {
  884.       /* But don't compare dir contents one level down
  885.          unless -r was specified.  */
  886.       message ("Common subdirectories: %s and %s\n",
  887.            inf[0].name, inf[1].name);
  888.       val = 0;
  889.     }
  890.       else
  891.     {
  892.       val = diff_dirs (inf, compare_files, depth);
  893.     }
  894.  
  895.     }
  896.   else if ((inf[0].dir_p | inf[1].dir_p)
  897.        || (depth > 0
  898.            && (! S_ISREG (inf[0].stat.st_mode)
  899.            || ! S_ISREG (inf[1].stat.st_mode))))
  900.     {
  901.       /* Perhaps we have a subdirectory that exists only in one directory.
  902.      If so, just print a message to that effect.  */
  903.  
  904.       if (inf[0].desc == -1 || inf[1].desc == -1)
  905.     {
  906.       if ((inf[0].dir_p | inf[1].dir_p)
  907.           && recursive
  908.           && (entire_new_file_flag
  909.           || (unidirectional_new_file_flag && inf[0].desc == -1)))
  910.         val = diff_dirs (inf, compare_files, depth);
  911.       else
  912.         {
  913.           char const *dir = (inf[0].desc == -1) ? dir1 : dir0;
  914.           /* See Posix.2 section 4.17.6.1.1 for this format.  */
  915.           message ("Only in %s: %s\n", dir, name0);
  916.           val = 1;
  917.         }
  918.     }
  919.       else
  920.     {
  921.       /* We have two files that are not to be compared.  */
  922.  
  923.       /* See Posix.2 section 4.17.6.1.1 for this format.  */
  924.       message5 ("File %s is a %s while file %s is a %s\n",
  925.             inf[0].name, filetype (&inf[0].stat),
  926.             inf[1].name, filetype (&inf[1].stat));
  927.  
  928.       /* This is a difference.  */
  929.       val = 1;
  930.     }
  931.     }
  932.   else if ((no_details_flag & ~ignore_some_changes)
  933.        && inf[0].stat.st_size != inf[1].stat.st_size
  934.        && (inf[0].desc == -1 || S_ISREG (inf[0].stat.st_mode))
  935.        && (inf[1].desc == -1 || S_ISREG (inf[1].stat.st_mode)))
  936.     {
  937.       message ("Files %s and %s differ\n", inf[0].name, inf[1].name);
  938.       val = 1;
  939.     }
  940.   else
  941.     {
  942.       /* Both exist and neither is a directory.  */
  943.       int o_binary = always_text_flag ? O_BINARY : 0;
  944.       /* Open the files and record their descriptors.  */
  945.  
  946.       if (inf[0].desc == -2)
  947.     if ((inf[0].desc = open (inf[0].name, O_RDONLY|o_binary, 0)) < 0)
  948.       {
  949.         perror_with_name (inf[0].name);
  950.         failed = 1;
  951.       }
  952.       if (inf[1].desc == -2)
  953.     if (same_files)
  954.       inf[1].desc = inf[0].desc;
  955.     else if ((inf[1].desc = open (inf[1].name, O_RDONLY|o_binary, 0)) < 0)
  956.       {
  957.         perror_with_name (inf[1].name);
  958.         failed = 1;
  959.       }
  960.  
  961.       /* Compare the files, if no error was found.  */
  962.  
  963.       val = failed ? 2 : diff_2_files (inf, depth);
  964.  
  965.       /* Close the file descriptors.  */
  966.  
  967.       if (inf[0].desc >= 0 && close (inf[0].desc) != 0)
  968.     {
  969.       perror_with_name (inf[0].name);
  970.       val = 2;
  971.     }
  972.       if (inf[1].desc >= 0 && inf[0].desc != inf[1].desc
  973.       && close (inf[1].desc) != 0)
  974.     {
  975.       perror_with_name (inf[1].name);
  976.       val = 2;
  977.     }
  978.     }
  979.  
  980.   /* Now the comparison has been done, if no error prevented it,
  981.      and VAL is the value this function will return.  */
  982.  
  983.   if (val == 0 && !inf[0].dir_p)
  984.     {
  985.       if (print_file_same_flag)
  986.     message ("Files %s and %s are identical\n",
  987.          inf[0].name, inf[1].name);
  988.     }
  989.   else
  990.     fflush (stdout);
  991.  
  992.   if (free0)
  993.     free (free0);
  994.   if (free1)
  995.     free (free1);
  996.  
  997.   return val;
  998. }
  999.